<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="40%"
    :close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" />
      </el-form-item>

      <el-form-item label="标准名称" prop="roleNormalizedName">
        <el-input v-model="form.roleNormalizedName" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handlerConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, defineProps, watch } from "vue";
import { createRole, updateRole } from "@/api/role";
import { ElMessage } from "element-plus";

const formRef = ref("");
const form = ref({
  roleId: "",
  roleName: "",
  roleNormalizedName: "",
  roleConcurrencyStamp: "",
});

const props = defineProps({
  dialogTitle: {
    type: String,
    default: "",
    required: true,
  },
  dialogTableValue: {
    type: Object,
    default: () => ({}),
  },
  dialogVisible: {
    type: Boolean,
    default: false,
  },
});

watch(
  () => props.dialogTableValue,
  () => {
    form.value = { ...props.dialogTableValue };
  },
  { deep: true, immediate: true }
);

const rules = ref({
  roleName: [
    {
      required: true,
      message: "请输入角色名称",
      trigger: "change",
    },
    {
      max: 256,
      message: "角色名称不能超过256个字符",
      trigger: "change",
    },
  ],
  roleNormalizedName: [
    {
      max: 256,
      message: "标准名称不能超过256个字符",
      trigger: "change",
    },
  ],
});

const emits = defineEmits(["update:modelValue", "initGetList"]);

const handleClose = () => {
  emits("update:modelValue", false);
};

const handlerConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (props.dialogTitle === "添加角色") {
          await createRole(form.value);
        } else {
          await updateRole(form.value);
        }
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        emits("initGetList");
        handleClose();
      } catch (error) {
        console.error("操作失败:", error);
      }
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

